from django.db import models, transaction
from django.contrib.auth import get_user_model
from django.conf import settings
UserModel = get_user_model()


class PreDepositLogManage(models.Manager):
    def create(self, **validated_data):
        print('读取设置', settings.INTEGRAL)
        operationMoney = validated_data['operationMoney']
        user = validated_data['user']
        operationType = validated_data['operationType']

        with transaction.atomic():
            preDepositLog = self.model(operationType=operationType, operationMoney=operationMoney, user=user)
            # UserModel.objects.add_pre_deposit(user=user, pre_deposit=operationMoney)
            if operationType == 1:
                user.preDeposit += operationMoney
                if operationMoney < 0:
                    user.totalConsumption += abs(operationMoney)
                else:

                    integral = 1
                    if settings.INTEGRAL:
                        integral = settings.INTEGRAL
                    user.integral += operationMoney // integral
                    pre = self.model(operationType=2, operationMoney=user.integral, user=user)
                    pre.save(using=self._db)
            else:
                user.integral += operationMoney
            user.save(update_fields=['preDeposit', 'integral', 'totalConsumption'])
            preDepositLog.save(using=self._db)

            return preDepositLog

    def create_integral(self, **validated_data):
        # operationMoney = validated_data['operationMoney']
        # user = validated_data['user']
        # operationType = 2
        #
        # with transaction.atomic():
        #     preDepositLog = self.model(operationType=operationType, operationMoney=operationMoney, user=user)
        #     # UserModel.objects.add_pre_deposit(user=user, pre_deposit=operationMoney)
        #     user.integral += operationMoney
        #     user.save(update_fields=['integral'])
        #     preDepositLog.save(using=self._db)
        #
        #     return preDepositLog
        if not validated_data.get('operationType', None):
            validated_data.setdefault('operationType', 2)
        return self.create(**validated_data)

